package com.johngene.mapapp;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.IReGeoLocationCallback;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.PoiItemV2;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.poisearch.PoiResultV2;
import com.amap.api.services.poisearch.PoiSearchV2;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;


public class MainActivity extends AppCompatActivity {
    private MapView mMapView = null;
    private AMap aMap=null;
    private UiSettings mUiSettings=null;
    private Marker marker=null;
    //声明AMapLocationClient类对象

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            // 已获取权限，可以进行定位操作
        } else {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        }

        setContentView(R.layout.activity_main);
        initMap();
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
    }

    private void initMap(){

        //String sha1=getSHA1(this);
        //MapsInitializer.setApiKey(sha1);//设置SHA1Key
        //隐私合规性
        MapsInitializer.updatePrivacyShow(this,true,true);
        MapsInitializer.updatePrivacyAgree(this,true);
        //搜索合规性
        ServiceSettings.updatePrivacyShow(this,true,true);
        ServiceSettings.updatePrivacyAgree(this,true);
        MapsInitializer.setTerrainEnable(true);//打开3D开关
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map1);

        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        if(mUiSettings==null){
            mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        }
        mUiSettings.setCompassEnabled(true);//显示指南针
        mUiSettings.setScaleControlsEnabled(true);//显示比例
        mUiSettings.setMyLocationButtonEnabled(true); //显示默认的定位按钮

        aMap.setOnMapClickListener(this::onMapClick);

        //初始化定位
//        try {
//            AMapLocationClient mLocationClient = new AMapLocationClient(getApplicationContext());
//            //初始化AMapLocationClientOption对象
//            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
//            mLocationOption.setOnceLocation(true);//单次定位
//            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
//            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//            //设置定位回调监听
//            /*mLocationClient.setLocationListener((AMapLocation aMapLocation)->{
//                if (aMapLocation != null) {
//                    if (aMapLocation.getErrorCode() == 0) {
//                        //可在其中解析amapLocation获取相应内容。
//                        Log.i("坐标", "onLocationChanged: "+aMapLocation.getLongitude()+","+aMapLocation.getLatitude());
//                        //Toast.makeText(MainActivity.this,"当前位置坐标: "+aMapLocation.getLongitude()+","+aMapLocation.getLatitude(),Toast.LENGTH_LONG).show();
//                    }else {
//                        //Toast.makeText(MainActivity.this,"获取位置失败: "+aMapLocation.getErrorInfo(),Toast.LENGTH_LONG).show();
//                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
//                        Log.e("AmapError","location Error, ErrCode:"
//                                + aMapLocation.getErrorCode() + ", errInfo:"
//                                + aMapLocation.getErrorInfo());
//                    }
//                }
//            });*/
//
//            //给定位客户端对象设置定位参数
//            mLocationClient.setLocationOption(mLocationOption);
//            //启动定位
//            mLocationClient.startLocation();
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }

        //显示定位
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位一次，且将视角移动到地图中心点。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点，用于满足只想使用定位，不想使用定位小蓝点的场景，设置false以后图面上不再有定位蓝点的概念，但是会持续回调位置信息。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    public static String getSHA1(Context context){
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length()-1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    private void onMapClick(LatLng latLng) {
        double longitude = latLng.longitude;
        double latitude = latLng.latitude;
        if(marker!=null){
            marker.remove();
        }
        marker = aMap.addMarker(new MarkerOptions().position(latLng).title("点位").snippet("DefaultMarker"));

        // 获取系统剪贴板服务
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

        // 创建一个包含文本的ClipData对象
        ClipData clip = ClipData.newPlainText("simple text", longitude+","+latitude);

        // 把ClipData对象放到系统剪贴板中
        clipboard.setPrimaryClip(clip);

        // 显示获取的经纬度信息
        Toast.makeText(this, "已复制粘贴板，经度: " + longitude + ", 纬度: " + latitude, Toast.LENGTH_SHORT).show();
    }

}